package servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.CommentEntityFacadeLocal;
import dao.ContentStatisticEntityFacadeLocal;
import entities.CommentEntity;
import entities.ContentEntity;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

/**
 * 
 * @author andrei costache
 *
 */
public class ContentFullViewController extends ContentController{
	
        @EJB CommentEntityFacadeLocal commentDAO;
        @EJB ContentStatisticEntityFacadeLocal statisticsDAO;
	
	@Override
	public void doRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
            RequestDispatcher view = null;
            String cid = request.getParameter("cid");
            if (cid != null){
                ContentEntity content = contentDAO.find(new Long(cid));
                //Check if a new comment has to be stored.
                String submitted = request.getParameter("submitted");
                if (submitted != null){
                    CommentEntity comment = new CommentEntity();
                    comment.setAuthor("An Author");
                    comment.setComment(request.getParameter("comment"));
                    comment.setCon_id(content.getCid());
                    comment.setChanged(System.currentTimeMillis()/1000);
                    comment.setCreatd(System.currentTimeMillis()/1000);
                    comment.setParent_id(new Long(0));
                    comment.setSubject(request.getParameter("subject"));
                    comment.setUid(new Long(0));
                    commentDAO.create(comment);
                    //JacksonJsonProvider test = new JacksonJsonProvider();
                    //JSONObject obj = new JSONObject();
                    //System.out.println(request.getHeaderNames());
                    //PrintWriter out = response.getWriter();
                    //out.println("this is ok");
                    //out.close();
                    //System.exit(0);
                    //System.ex
                    view = request.getRequestDispatcher("/jsp/CommentsViewAjax.jsp");
                } else {
                    view = request.getRequestDispatcher("/jsp/ContentFullView.jsp");
                }
                //Inject the content and the comments.
                request.setAttribute("content", content);
                request.setAttribute("comments", commentDAO.findAllByContent(content.getCid()));
                view.forward(request, response);
            }
            
	}
	

}
